package com.salton123.soulove.sailfish.video.ui.aty

import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.lifecycleScope
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.FileUtils
import com.hjq.toast.ToastUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.salton123.soulove.app.R
import com.salton123.soulove.common.Constants
import com.salton123.soulove.sailfish.video.SailfishManager
import com.salton123.soulove.sailfish.video.SailfishManager.toPlayVideoList
import com.salton123.soulove.sailfish.video.ui.adapter.VideoPlayAdapterStyle
import com.salton123.soulove.sailfish.video.widget.SailfishVideoController
import com.salton123.soulove.utils.Utils
import com.salton123.ui.base.BaseActivity
import com.yc.kernel.inter.AbstractVideoPlayer
import com.yc.video.config.ConstantKeys.CurrentState
import com.yc.video.player.SimpleStateListener
import com.yc.video.player.VideoPlayer
import com.yc.video.tool.PlayerUtils
import kotlinx.android.synthetic.main.activity_video_play_style.mViewPager
import kotlinx.coroutines.launch

@Route(path = Constants.Router.Video.PLAY)
class VideoPlayStyleActivity : BaseActivity() {
    private lateinit var videoPlayAdapterStyle: VideoPlayAdapterStyle
    private var videoPlayer: VideoPlayer<AbstractVideoPlayer>? = null
    private lateinit var controller: SailfishVideoController
    override fun enableTitleBar(): Boolean = false
    override fun getLayoutId(): Int = R.layout.activity_video_play_style

    override fun initViewAndData(bundle: Bundle?) {
        controller = SailfishVideoController(this)
        controller.setCanChangeBrightness(false)
        controller.setCanChangeVolume(false)
        videoPlayer = VideoPlayer(this)
        videoPlayer?.apply {
            setLooping(true)
            setController(controller)
            setOnStateChangeListener(object : SimpleStateListener() {
                override fun onPlayStateChanged(playState: Int) {
                    super.onPlayStateChanged(playState)
                    if (playState == CurrentState.STATE_ERROR) {
                        showDeleteItemDialog(url)
                    }
                }
            })
        }
        videoPlayAdapterStyle = VideoPlayAdapterStyle()
        videoPlayAdapterStyle.setData(toPlayVideoList)
        mViewPager.apply {
            offscreenPageLimit = 4
            adapter = videoPlayAdapterStyle
            adapter.notifyDataSetChanged()
            overScrollMode = View.OVER_SCROLL_NEVER
            setOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    startPlay(position)
                }
            })
            val index = intent.getIntExtra("index", 0)
            currentItem = index
            post { startPlay(index) }
        }
    }

    private fun startPlay(position: Int) {
        mViewPager.childCount.let {
            for (i in 0 until it) {
                val viewHolder = mViewPager.getChildAt(i).tag as VideoPlayAdapterStyle.ViewHolder
                if (viewHolder.position == position) {
                    controller.apply {
                        videoPlayAdapterStyle.getItem(position)?.let { videoItem ->
                            val filePath = videoItem.filePath
                            if (!FileUtils.isFileExists(filePath)) {
                                lifecycleScope.launch {
                                    videoPlayAdapterStyle.removeItem(videoItem)
                                    SailfishManager.deleteVideo(videoItem)
                                }
                                ToastUtils.show(getString(R.string.invalidate_video_resource))
                                finish()
                                return@apply
                            }
                            setTitle(videoItem.name)
                            findViewById<ImageView>(R.id.deleteBtn).setOnClickListener {
                                showDeleteItemDialog(filePath)
                            }
                            if (position < videoPlayAdapterStyle.getData().size) {
                                videoPlayer?.apply {
                                    release()
                                    PlayerUtils.removeViewFormParent(this)
                                    viewHolder.flContainer.addView(this, 0)
                                    url = filePath
                                    start()
                                }
                            } else {
                                ToastUtils.show(getString(R.string.play_all_video_finish))
                                finish()
                            }
                        } ?: kotlin.run {
                            ToastUtils.show(getString(R.string.play_all_video_finish))
                            finish()
                        }
                    }
                    break
                }
            }
        }
    }

    private var isDeleteDialogShow = false
    private fun showDeleteItemDialog(filePath: String) {
        videoPlayAdapterStyle.getData().find { it.filePath == filePath }?.let { videoItem ->
            val position = videoPlayAdapterStyle.getData().indexOf(videoItem)
            if (!isDeleteDialogShow) {
                isDeleteDialogShow = true
                XPopup.Builder(activity())
                    .setPopupCallback(object : SimpleCallback() {
                        override fun onDismiss(popupView: BasePopupView?) {
                            isDeleteDialogShow = false
                        }
                    })
                    .asConfirm(getString(R.string.delete_file),
                        Utils.getFilePath(filePath),
                        getString(R.string.common_cancel),
                        getString(R.string.common_delete),
                        {
                            lifecycleScope.launch {
                                videoPlayAdapterStyle.removeItem(videoItem)
                                SailfishManager.deleteVideo(videoItem)
                                if (videoPlayAdapterStyle.getData().isNotEmpty()) {
                                    startPlay(position)
                                } else {
                                    finish()
                                    ToastUtils.show(getString(R.string.play_all_video_finish))
                                }
                            }
                        }, {}, false, 0
                    )

                    .show()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        videoPlayer?.apply {
            clearOnStateChangeListeners()
            release()
        }
    }

    override fun onResume() {
        super.onResume()
        videoPlayer?.resume()
    }

    override fun onPause() {
        super.onPause()
        videoPlayer?.pause()
    }

    override fun onBackPressedSupport() {
        if (videoPlayer?.onBackPressed() == false) {
            super.onBackPressedSupport()
        }
    }
}